package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.xxxx.server.mapper.MenuRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.MenuRole;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
    private MenuRoleMapper menuRoleMapper;

	/**
	 * 根据用户id查询角色
	 *
	 * @return
	 */
	@Override
	public List<Role> getRolesByAdminId(Integer adminId) {
		return roleMapper.getRolesByAdminId(adminId);
	}

	@Override
    public boolean save(Role role){
        checkParam(role);
	    return SqlHelper.retBool(getBaseMapper().insert(role));
    }

    public void checkParam(Role role){
        Assert.notNull(role,"权限不能空");
        String name = role.getName();
        if (!name.startsWith("ROLE_")) {
            name = "ROLE_" + name;
        }
        role.setName(name);
    }

    @Transactional
    @Override
    public boolean removeById(Serializable id) {
        Assert.isTrue((int)id > 0,"不合法");
        Assert.notNull( baseMapper.selectById(id),"该记录不存在");
        menuRoleMapper.delete(new QueryWrapper<MenuRole>().eq("rid",id));
        return SqlHelper.retBool(getBaseMapper().deleteById(id));
    }
}
